package com.kzd.gtboon.main.game

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.kzd.gtboon.custom.setTransitionStatusE
import com.kzd.gtboon.databinding.IncludeAppRefreshBinding
import com.kzd.gtboon.entity.GameBean
import com.kzd.gtboon.jetpack.vm.GameViewModel
import com.kzd.gtboon.main.game.adapter.Game1Adapter
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel

class GameListFragment : OwnerViewBindingFragment<IncludeAppRefreshBinding>() {

    companion object {
        private const val KEY_GAME_LIST_TYPE = "KEY_GAME_LIST_TYPE"
        fun newInstance(type: String): GameListFragment {
            val bundle = Bundle().apply {
                putString(KEY_GAME_LIST_TYPE, type)
            }
            return GameListFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mGame1Adapter:Game1Adapter<GameBean> by lazy {
        Game1Adapter(Game1Adapter.Type.GAME_LIST_CLASSIFY)
    }

    private val mType: String by lazy {
        arguments?.getString(KEY_GAME_LIST_TYPE) ?: "0"
    }

    private val mViewModel:GameViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> IncludeAppRefreshBinding
        get() = IncludeAppRefreshBinding::inflate

    override fun initView() {
        mViewBinding.rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = mGame1Adapter

        mViewBinding.mSmartRefreshLayout.setOnRefreshListener {
            mViewModel.gameList(mType)
        }
        mViewBinding.mSmartRefreshLayout.setOnLoadMoreListener {
            mViewModel.gameList(mType, isLoadMore = true)
        }
    }

    override fun initData() {
        mViewModel.gameList(mType)
    }

    override fun initViewMode() {
        mViewModel.gameListLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response, mGame1Adapter, mViewBinding.mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?:return@observe
            val isLoadMore = response.data?.isLoadMore
                ?:return@observe
            if (isLoadMore) {
                mGame1Adapter.addData(data)
            } else {
                mGame1Adapter.setNewInstance(data)
            }
        })
    }
}